package com.icarsaas.saas.component.fileUpload.config;

import com.icarsaas.saas.common.utils.SpringContextUtil;
import com.icarsaas.saas.component.fileUpload.FileUploadUtil;
import com.icarsaas.saas.component.fileUpload.config.properties.UploadProjectProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Configuration
public class UploadFileConfigurer implements WebMvcConfigurer {

    @Autowired @Qualifier("thymeleafViewResolver")
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 设置静态路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        UploadProjectProperties properties = SpringContextUtil.getBean(UploadProjectProperties.class);
        registry.addResourceHandler(properties.getStaticPath()).addResourceLocations("file:" + FileUploadUtil.getUploadPath());
    }

    /**
     * thymeleaf 静态变量
     * @param registry
     */
    public void configureViewResolvers(ViewResolverRegistry registry) {
        if (thymeleafViewResolver != null) {
            UploadProjectProperties properties = SpringContextUtil.getBean(UploadProjectProperties.class);
            String ctxStatic = properties.getStaticPath().replace("/**", "");
            Map<String, Object> map = new HashMap<>();
            String ctx = SpringContextUtil.getContextPath();
            if (StringUtils.isEmpty(ctx)) ctx = "";
//            log.info("上下文路径ctx=" + ctx);
//            log.info("静态文件路径ctxStatic=" + ctxStatic);
            map.put("ctx", ctx);
            map.put("ctxStatic", ctx + ctxStatic);
            thymeleafViewResolver.setStaticVariables(map);
        }
    }

}
